<template>
  <div class="course-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>课程管理</h2>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索课程"
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="categoryFilter"
              placeholder="课程分类"
              class="filter-item"
              @change="handleSearch"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              添加课程
            </el-button>
          </div>
        </div>
      </template>

      <!-- 课程列表 -->
      <el-table
        v-loading="loading"
        :data="courseList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="课程信息" min-width="300">
          <template #default="{ row }">
            <div class="course-info">
              <el-image
                :src="row.cover"
                class="course-cover"
                fit="cover"
              />
              <div class="course-detail">
                <div class="course-title">{{ row.title }}</div>
                <div class="course-desc">{{ row.description }}</div>
                <div class="course-meta">
                  <el-tag size="small">{{ row.category }}</el-tag>
                  <el-tag size="small" type="success">{{ row.level }}</el-tag>
                  <span class="price">¥{{ row.price }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="讲师" width="120">
          <template #default="{ row }">
            <div class="teacher-info">
              <el-avatar :size="24" :src="row.teacher.avatar" />
              <span>{{ row.teacher.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="students" label="学员数" width="100" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" link @click="handleContent(row)">
              内容
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加课程' : '编辑课程'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="课程分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程封面">
          <el-upload
            class="cover-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
          >
            <img v-if="form.cover" :src="form.cover" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="课程难度" prop="level">
          <el-select v-model="form.level" placeholder="请选择难度">
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="10"
          />
        </el-form-item>
        <el-form-item label="讲师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择讲师">
            <el-option
              v-for="item in teachers"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 课程内容对话框 -->
    <el-dialog
      v-model="contentDialogVisible"
      title="课程内容管理"
      width="1000px"
    >
      <div class="content-header">
        <el-button type="primary" @click="handleAddChapter">
          <el-icon><Plus /></el-icon>
          添加章节
        </el-button>
      </div>
      <el-tree
        :data="courseContent"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="actions">
              <el-button type="primary" link @click="handleEditNode(data)">
                编辑
              </el-button>
              <el-button type="success" link @click="handleAddNode(data)">
                添加
              </el-button>
              <el-button type="danger" link @click="handleDeleteNode(node, data)">
                删除
              </el-button>
            </span>
          </div>
        </template>
      </el-tree>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和筛选
const searchQuery = ref('')
const categoryFilter = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 课程列表
const courseList = ref([])

// 分类列表
const categories = ref([
  { id: 1, name: '前端开发' },
  { id: 2, name: '后端开发' },
  { id: 3, name: '移动开发' },
  { id: 4, name: '数据库' },
  { id: 5, name: '人工智能' }
])

// 讲师列表
const teachers = ref([
  { id: 1, name: '张老师', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
  { id: 2, name: '李老师', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
  { id: 3, name: '王老师', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: null,
  title: '',
  categoryId: '',
  cover: '',
  description: '',
  level: '初级',
  price: 0,
  teacherId: '',
  status: 1
})

// 课程内容对话框
const contentDialogVisible = ref(false)
const courseContent = ref([])

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入课程简介', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择课程难度', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入课程价格', trigger: 'blur' }
  ],
  teacherId: [
    { required: true, message: '请选择讲师', trigger: 'change' }
  ]
}

// 获取课程列表
const fetchCourseList = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取课程列表
    // 这里模拟数据
    const mockData = Array.from({ length: 9 }, (_, index) => ({
      id: index + 1,
      title: `课程${index + 1}`,
      description: '这是一门非常棒的课程，快来学习吧！',
      cover: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      category: categories.value[index % categories.value.length].name,
      level: ['初级', '中级', '高级'][index % 3],
      price: Math.floor(Math.random() * 1000),
      teacher: teachers.value[index % teachers.value.length],
      students: Math.floor(Math.random() * 1000),
      rating: (Math.random() * 2 + 3).toFixed(1),
      status: 1
    }))
    
    // 模拟搜索和筛选
    let filteredData = mockData
    if (searchQuery.value) {
      filteredData = filteredData.filter(course => 
        course.title.includes(searchQuery.value) ||
        course.description.includes(searchQuery.value)
      )
    }
    if (categoryFilter.value) {
      filteredData = filteredData.filter(course => 
        course.category === categories.value.find(c => c.id === categoryFilter.value)?.name
      )
    }
    
    total.value = filteredData.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    courseList.value = filteredData.slice(start, end)
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCourseList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCourseList()
}

// 添加课程
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    id: null,
    title: '',
    categoryId: '',
    cover: '',
    description: '',
    level: '初级',
    price: 0,
    teacherId: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑课程
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    title: row.title,
    categoryId: categories.value.find(c => c.name === row.category)?.id,
    cover: row.cover,
    description: row.description,
    level: row.level,
    price: row.price,
    teacherId: row.teacher.id,
    status: row.status
  })
  dialogVisible.value = true
}

// 删除课程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该课程吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // TODO: 调用API删除课程
    const index = courseList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      courseList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 修改课程状态
const handleStatusChange = async (row) => {
  try {
    // TODO: 调用API修改课程状态
    ElMessage.success(`课程${row.status === 1 ? '上架' : '下架'}成功`)
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error('修改状态失败')
    row.status = row.status === 1 ? 0 : 1 // 恢复状态
  }
}

// 课程内容管理
const handleContent = (row) => {
  // TODO: 调用API获取课程内容
  courseContent.value = [
    {
      id: 1,
      label: '第一章：课程介绍',
      children: [
        {
          id: 11,
          label: '1.1 课程概述'
        },
        {
          id: 12,
          label: '1.2 学习目标'
        }
      ]
    },
    {
      id: 2,
      label: '第二章：基础知识',
      children: [
        {
          id: 21,
          label: '2.1 环境搭建'
        },
        {
          id: 22,
          label: '2.2 基本概念'
        }
      ]
    }
  ]
  contentDialogVisible.value = true
}

// 添加章节
const handleAddChapter = () => {
  courseContent.value.push({
    id: Date.now(),
    label: '新章节',
    children: []
  })
}

// 编辑节点
const handleEditNode = (data) => {
  // TODO: 实现编辑节点功能
  ElMessage.info('编辑节点功能开发中')
}

// 添加节点
const handleAddNode = (data) => {
  if (!data.children) {
    data.children = []
  }
  data.children.push({
    id: Date.now(),
    label: '新课时'
  })
}

// 删除节点
const handleDeleteNode = (node, data) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex(d => d.id === data.id)
  children.splice(index, 1)
}

// 封面上传
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传封面只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传封面图片大小不能超过 2MB!')
    return false
  }

  // 模拟上传
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    form.cover = reader.result
  }
  return false
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // TODO: 调用API保存课程
    if (dialogType.value === 'add') {
      // 模拟添加课程
      const newCourse = {
        id: courseList.value.length + 1,
        title: form.title,
        description: form.description,
        cover: form.cover,
        category: categories.value.find(c => c.id === form.categoryId)?.name,
        level: form.level,
        price: form.price,
        teacher: teachers.value.find(t => t.id === form.teacherId),
        students: 0,
        rating: 5.0,
        status: form.status
      }
      courseList.value.unshift(newCourse)
    } else {
      // 模拟更新课程
      const index = courseList.value.findIndex(course => course.id === form.id)
      if (index > -1) {
        Object.assign(courseList.value[index], {
          title: form.title,
          description: form.description,
          cover: form.cover,
          category: categories.value.find(c => c.id === form.categoryId)?.name,
          level: form.level,
          price: form.price,
          teacher: teachers.value.find(t => t.id === form.teacherId),
          status: form.status
        })
      }
    }
    dialogVisible.value = false
    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  fetchCourseList()
})
</script>

<style scoped>
.course-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.filter-item {
  width: 150px;
}

.course-info {
  display: flex;
  gap: 15px;
}

.course-cover {
  width: 120px;
  height: 80px;
  border-radius: 4px;
}

.course-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.course-title {
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.course-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin: 5px 0;
}

.course-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.teacher-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cover-uploader {
  text-align: center;
}

.cover-uploader .cover {
  width: 300px;
  height: 180px;
  object-fit: cover;
}

.cover-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.cover-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 180px;
  text-align: center;
  line-height: 180px;
}

.content-header {
  margin-bottom: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.actions {
  display: flex;
}

.button-new-tag {
  margin-left: 10px;
  vertical-align: bottom;
}
</style> 